<!-- 设备管理-设备列表页面 -->
<template>
  <div class="app-container">
    <px-form v-show="showSearch" ref="queryRef" class="custom-form-ui" :model="queryParams" :inline="true" label-width="90px">
      <px-form-item label="排放因子名称">
        <px-input v-model="queryParams.emissionFactorName" :maxlength="50" placeholder="请输入" clearable />
      </px-form-item>
      <px-form-item label="排放因子来源">
        <px-select v-model="queryParams.factorSource" placeholder="请选择" clearable style="width: 240px" filterable>
          <px-option v-for="dict in SourceList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemName" />
        </px-select>
      </px-form-item>
      <px-form-item label="发布时间">
        <px-date-picker v-model="queryParams.releaseYear" type="year" value-format="YYYY" placeholder="请选择年份" />
      </px-form-item>
      <px-button style="margin-top: -17px" type="primary" icon="" @click="handleQuery('search')">搜索</px-button>
      <px-button style="margin-top: -17px" icon="" @click="resetQuery">重置</px-button>
    </px-form>

    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'FACTOR_ADD'" type="primary" icon="" @click="handleAdd">新增</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'FACTOR_INTO'" type="primary" plain icon="" @click="handleImport">导入</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'FACTOR_EXPORT'" type="primary" plain icon="" @click="handleExport">导出</px-button>
      </px-col>
    </px-row>
    <px-dialog v-model="dialogVisible" title="导入数据" :width="600">
      <div class="import-bottle">
        <div class="import-bottle-title">
          上传前请先
          <span class="download" @click="handleDown()"> 下载模板 </span>
          ，填写完成后导入数据
        </div>
        <div class="import-bottle-upload">
          <importFiles v-model="importFile" :uploadApi="emissionFactoruploadFile" @submit="submitHandler" />
        </div>
      </div>
    </px-dialog>
    <px-table v-if="!addVisible && !detailVisible" v-loading="loading" :data="typeList" height="calc(100vh - 319px)" border>
      <px-table-column label="序号" fixed="left" type="index" width="70">
        <template #default="{ $index }">
          {{ $index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize }}
        </template>
      </px-table-column>

      <px-table-column label="排放因子名称" width="340" prop="name">
        <template #default="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </px-table-column>

      <px-table-column label="产生的GHG种类" width="160" prop="gasType">
        <template #default="scope">
          <span>{{ scope.row.gasType }}</span>
        </template>
      </px-table-column>

      <px-table-column label="排放因子" width="98" prop="value">
        <template #default="scope">
          <span>{{ scope.row.value }}</span>
        </template>
      </px-table-column>
      <px-table-column label="排放因子单位" width="120" prop="unit">
        <template #default="scope">
          <span>{{ scope.row.unit }}</span>
        </template>
      </px-table-column>
      <px-table-column label="排放因子来源" width="120" prop="factorSource">
        <template #default="scope">
          <span>{{ scope.row.factorSource }}</span>
        </template>
      </px-table-column>
      <px-table-column label="发布时间" width="86" prop="releaseYear">
        <template #default="scope">
          <span>{{ scope.row.releaseYear }}</span>
        </template>
      </px-table-column>
      <px-table-column label="来源文件">
        <template #default="scope">
          <span
            v-for="button in scope.row.fileDTOS"
            :key="button.id"
            style="width: 600px; color: #3b82f6; text-align: left; cursor: pointer"
            @click="handleFileBrowsedetail(button)"
            >{{ button.originalName }}</span
          >
        </template>
      </px-table-column>
      <px-table-column label="创建人" width="120" prop="createByName">
        <template #default="scope">
          <span>{{ scope.row.createByName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="创建时间" prop="createTime">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </px-table-column>

      <px-table-column label="修改人" width="100" prop="receiveCompany">
        <template #default="scope">
          <span>{{ scope.row.updateByName }}</span>
        </template>
      </px-table-column>
      <px-table-column label="修改时间" prop="outboundTime">
        <template #default="scope">
          <span>{{ scope.row.updateTime }}</span>
        </template>
      </px-table-column>
      <px-table-column fixed="right" label="操作" align="center" width="140">
        <template #default="scope">
          <px-button v-has="'FACTOR_DETAIL'" link type="primary" @click="handleDetail(scope.row.id)">
            <px-tooltip class="box-item" content="详情" placement="top">
              <px-icon>
                <Tickets />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" v-has="'FACTOR_EDITOR'" link type="primary" @click="handleEditor(scope.row.id)">
            <px-tooltip class="box-item" content="编辑" placement="top">
              <px-icon>
                <EditPen />
              </px-icon> </px-tooltip
          ></px-button>
          <px-button v-if="scope.row.status != 'INVALID'" v-has="'FACTOR_DELETE'" link type="danger" @click="handleDelete(scope.row)"
            ><px-tooltip class="box-item" content="删除" placement="top">
              <px-icon>
                <Delete />
              </px-icon> </px-tooltip
          ></px-button>
        </template>
      </px-table-column>
      <template #empty>
        <px-empty :image-size="150" />
      </template>
    </px-table>

    <pagination
      v-if="!equipopen && !equipopenDetail"
      v-show="total > 0"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      style="margin-bottom: -10px"
      :total="total"
      @pagination="getList"
    />
    <px-scrollbar v-if="addVisible" class="addEquip">
      <div class="flex items-center justify-between pl-6 pr-6">
        <px-button type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel">返回</px-button>
        <px-button v-if="buttonTitle === '编辑'" type="primary" @click="openHistoryVersion">历史版本</px-button>
      </div>
      <px-form
        ref="detailruleFormRef"
        :disabled="fromdisable"
        :rules="rules"
        :model="equipdata"
        :inline="true"
        class="demo-form-inline"
        label-width="160px"
      >
        <div
          class="box-card1"
          :style="{
            height: jibenxinxiFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setqingdanFlg()">
            <div class="card-title">排放因子信息</div>
            <div class="card-main">
              <px-icon v-if="!jibenxinxiFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="12">
                <px-form-item label="排放因子名称" prop="emissionFactorName">
                  <px-input v-model="equipdata.emissionFactorName" :maxlength="60" placeholder="请输入排放因子名称" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="排放因子单位" prop="numberatorUnit">
                  <px-select v-model="equipdata.numberatorUnit" style="width: calc(50% - 40px)" placeholder="选择分子单位" clearable filterable>
                    <px-option v-for="dict in zUnitList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemName" /> </px-select
                  ><span>&nbsp;/&nbsp; </span>
                  <px-select v-model="equipdata.denominatorUnit" style="width: calc(50% - 40px)" placeholder="选择分母单位" filterable>
                    <px-option v-for="dict in mUnitList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemName" />
                  </px-select>
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="12">
                <px-form-item label="排放因子来源" prop="factorSource">
                  <px-select v-model="equipdata.factorSource" style="width: calc(100% - 70px)" placeholder="请选择排放因子来源" clearable filterable>
                    <px-option v-for="dict in SourceList" :key="dict.itemName" :label="dict.itemName" :value="dict.itemName" />
                  </px-select>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="发布年份" prop="releaseYear">
                  <px-date-picker
                    v-model="equipdata.releaseYear"
                    style="width: calc(100% - 70px)"
                    type="year"
                    value-format="YYYY"
                    placeholder="请选择年份"
                    @change="changeYearVersion"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>
        <div
          class="box-card1"
          :style="{
            height: numFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setnumFlg()">
            <div class="card-title">排放因子温室气体与数值</div>
            <div class="card-main">
              <px-icon v-if="!numFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <div class="form-div">
            <px-row>
              <px-col :span="8">
                <px-form-item label="CO₂">
                  <px-input-number
                    v-model="equipdata.CO2"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入CO₂"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="CH₄">
                  <px-input-number
                    v-model="equipdata.CH4"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入CH₄"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="N₂O">
                  <px-input-number
                    v-model="equipdata.N2O"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入N₂O"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="8">
                <px-form-item label="HFCs">
                  <px-input-number
                    v-model="equipdata.HFCs"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入HFCs"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="PFCs">
                  <px-input-number
                    v-model="equipdata.PFCs"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入PFCs"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="8">
                <px-form-item label="SF₆">
                  <px-input-number
                    v-model="equipdata.SF6"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入SF₆"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row>
              <px-col :span="8">
                <px-form-item label="NF₃">
                  <px-input-number
                    v-model="equipdata.NF3"
                    controls-position="right"
                    :max="9999999999.99999"
                    :min="0"
                    placeholder="请输入NF₃"
                    clearable
                    @blur="setCo2e"
                    @change="setCo2e"
                  />
                </px-form-item>
              </px-col>
            </px-row>
            <px-row style="width: calc(100% + 48px); margin-left: -24px; border-bottom: 1px solid #dfdfdf" />
            <px-row style="padding-top: 10px; margin-bottom: 0">
              <px-col :span="8" />

              <px-col :span="16">
                <px-form-item label="CO₂e" prop="CO2e">
                  <px-input v-model="equipdata.CO2e" style="width: 150px" :disabled="true" placeholder="自动计算CO₂e" clearable />
                  <px-tooltip class="box-item" effect="dark" content="CO₂e值为上面7项的总和" placement="top">
                    <px-icon style="margin-left: 8px; cursor: pointer">
                      <QuestionFilled color="#3B82F6" />
                    </px-icon>
                  </px-tooltip>
                </px-form-item>
              </px-col>
            </px-row>
          </div>
        </div>
        <div
          class="box-card2"
          style="margin-bottom: 50px"
          :style="{
            height: jiqicanshuFlg == true ? '' : '42px'
          }"
        >
          <div class="card-header" @click="setjiqicanshuFlg()">
            <div class="card-title">来源文件</div>
            <div class="card-main">
              <px-icon v-if="!jiqicanshuFlg">
                <ArrowDown />
              </px-icon>
              <px-icon v-else>
                <ArrowUp />
              </px-icon>
            </div>
          </div>
          <px-scrollbar class="form-div" style="padding-bottom: 10px">
            <div class="info-form-content">
              <FileUpload
                fileType="add"
                :fileSize="999"
                fileAccept=".pdf"
                fileTypeValue="pdf"
                :fileData="{ moduleName: 'GENERAL_CHEMICALS' }"
                :fileList="equipdata.documentIds"
                @changeFileList="changeFileList"
                @saveFileStatus="saveFileStatus"
              />
            </div>
          </px-scrollbar>
        </div>
      </px-form>
    </px-scrollbar>
    <px-scrollbar v-if="detailVisible" class="editorEquip">
      <div class="flex items-center justify-between pl-6 pr-6">
        <px-button style="margin-left: 24px" type="primary" :icon="ArrowLeft" @click="equipopenDetailcancel2">返回</px-button>
        <px-button type="primary" @click="openHistoryVersion">历史版本</px-button>
      </div>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">基本信息</div>
      <px-descriptions class="margin-top" style="padding: 20px" title="" :column="2" border>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">排放因子名称</div>
          </template>
          {{ equipdata.emissionFactorName }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">排放因子单位</div>
          </template>
          {{ equipdata.numberatorUnit }}/{{ equipdata.denominatorUnit }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">排放因子来源</div>
          </template>
          {{ equipdata.factorSource }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">发布年份</div>
          </template>
          {{ equipdata.releaseYear }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">修改人</div>
          </template>
          {{ equipdata.updateByName }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">修改时间</div>
          </template>
          {{ equipdata.updateTime }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">创建人</div>
          </template>
          {{ equipdata.createByName }}
        </px-descriptions-item>
        <px-descriptions-item>
          <template #label>
            <div class="cell-item">创建时间</div>
          </template>
          {{ equipdata.createTime }}
        </px-descriptions-item>
      </px-descriptions>
      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">排放因子温室气体与数值</div>
      <div style="padding: 0 20px">
        <px-table style="margin-top: 20px" :data="equipdata.factorValueDTOS" height="360px" border>
          <px-table-column label="温室气体类型" prop="cengji">
            <template #default="scope">
              <span>{{ scope.row.gasType }}</span>
            </template>
          </px-table-column>
          <px-table-column label="排放因子数值" prop="mubiao">
            <template #default="scope">
              <span>{{ scope.row.value == null ? "-" : scope.row.value }}</span>
            </template>
          </px-table-column>
        </px-table>
      </div>

      <div class="px-descriptions__title" style="margin: 20px 0 0 20px">来源文件</div>
      <div class="form-table" style="padding: 20px 20px 50px">
        <FileUpload
          fileType="view"
          :isPreview="true"
          :countLimit="1"
          :fileData="{ moduleName: 'GENERAL_CHEMICALS' }"
          :fileList="equipdata.documentIds"
        />
      </div>
    </px-scrollbar>
    <div v-if="addVisible" class="px-dialog-footer">
      <px-button @click="equipopenDetailcancel">取消</px-button>
      <px-button type="primary" @click="equipopenDetailsubmitForm(detailruleFormRef)">保存</px-button>
    </div>
    <historyList v-if="showHistoryDialog" v-model="showHistoryDialog" :name="equipdata.emissionFactorName" />
  </div>
</template>

<script setup name="Dict" lang="ts">
defineOptions({
  name: "SystemDataDict"
});
// import { router } from "@/router";
import { ArrowLeft } from "@px-ui/icons-vue";
import { useRouter } from "vue-router";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, ref, toRefs, reactive, onMounted } from "vue";
import { getToken } from "@/utils/auth";
import { queryChildByTypeCodeAndItemValue } from "@/api/waterClass";
import FileUpload from "@/components/Upload/FileUpload.vue";
import {
  emissionFactorquery,
  emissionFactorSourceList,
  emissionFactorsave,
  numberatorUnitList,
  denominatorUnitList,
  emissionFactordelete,
  emissionFactoredit,
  emissionFactordetail,
  emissionFactoruploadFile,
  getemissionFactorHistory
} from "@/api/doubleCarbonManage/carbonAccounting";
import importFiles from "./importFiles.vue";
import historyList from "./components/historyList.vue";
import { cloneDeep } from "@pureadmin/utils";

const handleDown = async (reportId, templateIdval) => {
  proxy.download("post", "/energy/api/v1/emissionFactor/downloadTemplate", {}, "排放因子导入模板.xlsx");
};
const router = useRouter();
const importFile = ref<string>("");
const jibenxinxiFlg = ref(true);
const jiqicanshuFlg = ref(true);
const numFlg = ref(true);
const submitHandler = value => {
  getList();
};
const setCo2e = () => {
  equipdata.value.CO2e =
    Math.round(
      (equipdata.value.CO2 == null ? 0 : equipdata.value.CO2) * 100000 +
        (equipdata.value.CH4 == null ? 0 : equipdata.value.CH4) * 100000 +
        (equipdata.value.N2O == null ? 0 : equipdata.value.N2O) * 100000 +
        (equipdata.value.HFCs == null ? 0 : equipdata.value.HFCs) * 100000 +
        (equipdata.value.PFCs == null ? 0 : equipdata.value.PFCs) * 100000 +
        (equipdata.value.SF6 == null ? 0 : equipdata.value.SF6) * 100000 +
        (equipdata.value.NF3 == null ? 0 : equipdata.value.NF3) * 100000
    ) / 100000;
  detailruleFormRef.value.validateField("CO2e");
};
const setqingdanFlg = () => {
  jibenxinxiFlg.value = !jibenxinxiFlg.value;
};
const setjiqicanshuFlg = () => {
  jiqicanshuFlg.value = !jiqicanshuFlg.value;
};
const handleFileBrowsedetail = row => {
  if (row != null) {
    const { id, fileName, moduleName, fileType: type = "" } = row;
    // doc 暂不支持预览
    const allowType = ["txt", "docx", "xls", "xlsx", "pdf", "png", "jpg", "jpeg", "mp4"];
    if (!allowType.includes(type)) {
      PxMessage.error("暂不支持该格式文件的预览");
      return;
    }
    const path = "/fullScreen/preview";
    const query = { id, fileName, moduleName, type };
    const params = { path, query };
    const { href } = router.resolve(params);
    window.open(href, "_blank");
  } else {
    PxMessage.error("没有可以预览的文件");
  }
};
const setnumFlg = () => {
  numFlg.value = !numFlg.value;
};
const defaultTime: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 1), new Date(2000, 1, 1, 23, 59, 59)];
const detailruleFormRef = ref();

onMounted(() => {
  if (localStorage.getItem("chukuList")) {
  }
});
const { proxy }: any = getCurrentInstance();
function equipopenDetailcancel() {
  console.log(buttonTitle.value);
  if (buttonTitle.value == "新增") {
    if (
      equipdata.value.emissionFactorName != "" ||
      equipdata.value.numberatorUnit != "" ||
      equipdata.value.denominatorUnit != "" ||
      equipdata.value.factorSource != "" ||
      equipdata.value.releaseYear != "" ||
      equipdata.value.CO2 != null ||
      equipdata.value.CH4 != null ||
      equipdata.value.N2O != null ||
      equipdata.value.HFCs != null ||
      equipdata.value.PFCs != null ||
      equipdata.value.SF6 != null ||
      equipdata.value.NF3 != null ||
      equipdata.value.CO2e != null ||
      equipdata.value.documentIds.length > 0
    ) {
      PxMessageBox.confirm("<p>取消将不保存当前录入信息返回上一页</p><p>确定取消吗？</p>", "温馨提示", {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          addVisible.value = false;
          getList();
        })
        .catch(() => {});
    } else {
      addVisible.value = false;
      getList();
    }
  } else {
    addVisible.value = false;
    getList();
  }
}
const equipopenDetailcancel2 = () => {
  detailVisible.value = false;
  getList();
};
const typeList = ref([]);
const progressVisible = ref(false);
const equipopen = ref(false);
const equipopenDetail = ref(false);
const fromdisable = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const dialogVisible = ref(false);
const addVisible = ref(false);
const detailVisible = ref(false);
const total = ref(0);
const total2 = ref(0);
const dateRange = ref([]);

// 图片是否上传完，是否可以保存
const buttonTitle = ref("");
const data = reactive({
  liquidList: [],
  rukuList: [],
  transportCompanyList: [],
  receiveCompanyList: [],
  typeIdList: [],
  categoryList: [],
  equipmentTypeList: [],
  positionList: [],
  selectRukuList: [],
  okselectRukuList: [],
  equipmentDeptList: [],
  modelIdList: [],
  form: {},
  photoStatusFlag: false,
  fileStatusFlag: false,
  SourceList: [],
  zUnitList: [],
  mUnitList: [],
  equipdata: {
    id: "",
    emissionFactorName: "",
    numberatorUnit: "",
    denominatorUnit: "",
    factorSource: "",
    releaseYear: "",
    CO2: null,
    CH4: null,
    N2O: null,
    HFCs: null,
    PFCs: null,
    SF6: null,
    NF3: null,
    CO2e: null,
    factorValueDTOS: [],
    createByName: "",
    updateByName: "",
    documentIds: []
  },
  queryParams: {
    orderByColumn: "",
    isAsc: "",
    emissionFactorName: "",
    factorSource: "",
    releaseYear: "",
    orderBy: "",
    pageNum: 1,
    pageSize: 20
  },
  rules: {
    emissionFactorName: [{ required: true, message: "排放因子名称不能为空", trigger: "blur" }],
    numberatorUnit: [{ required: true, message: "排放因子单位不能为空", trigger: "change" }],
    factorSource: [{ required: true, message: "排放因子来源不能为空", trigger: "change" }],
    releaseYear: [{ required: true, message: "发布年份不能为空", trigger: "blur" }],
    CO2e: [
      {
        validator: (rule: any, value: any, callback: any) => {
          if (value === null) {
            return callback(new Error("CO₂e不能为空"));
          } else if (
            equipdata.value.CO2 != null ||
            equipdata.value.CH4 != null ||
            equipdata.value.N2O != null ||
            equipdata.value.HFCs != null ||
            equipdata.value.PFCs != null ||
            equipdata.value.SF6 != null ||
            equipdata.value.NF3 != null
          ) {
            if (
              Number(value) !=
              Math.round(
                Number(
                  Number(equipdata.value.CO2 == null ? 0 : equipdata.value.CO2) * 100000 +
                    Number(equipdata.value.CH4 == null ? 0 : equipdata.value.CH4) * 100000 +
                    Number(equipdata.value.N2O == null ? 0 : equipdata.value.N2O) * 100000 +
                    Number(equipdata.value.HFCs == null ? 0 : equipdata.value.HFCs) * 100000 +
                    Number(equipdata.value.PFCs == null ? 0 : equipdata.value.PFCs) * 100000 +
                    Number(equipdata.value.SF6 == null ? 0 : equipdata.value.SF6) * 100000 +
                    Number(equipdata.value.NF3 == null ? 0 : equipdata.value.NF3) * 100000
                )
              ) /
                100000
            ) {
              return callback(new Error("CO₂e值必须为上面7项的总和"));
            }
          }
          callback();
        },
        trigger: "blur",
        required: true
      }
    ]
  },
  headers: {
    Authorization: "Bearer " + getToken().accessToken || ""
  },
  moduleName: "",
  dialogImageUrl: "",
  imageVisible: false
});
const { liquidList, fileStatusFlag, SourceList, selectRukuList, zUnitList, mUnitList, queryParams, form, rules, equipdata, rukuList } = toRefs(data);
const getqueryCategoryList = () => {
  queryChildByTypeCodeAndItemValue({
    value: "EMISSION_FACTOR_SOURCE",
    typeCode: "BICARBON"
  }).then((response: any) => {
    SourceList.value = response;
  });

  queryChildByTypeCodeAndItemValue({
    value: "NUMBERATOR_UNIT",
    typeCode: "BICARBON"
  }).then((response: any) => {
    zUnitList.value = response;
  });

  queryChildByTypeCodeAndItemValue({
    value: "DENOMINATOR_UNIT",
    typeCode: "BICARBON"
  }).then((response: any) => {
    mUnitList.value = response;
  });
};
getqueryCategoryList();
// 新的文件列表
const changeFileList = val => {
  // equipdata.value.documentIds = val;
  console.log(val);
};
// 文件是否上传完，是否可以保存
const saveFileStatus = val => {
  fileStatusFlag.value = val;
};
const handledelAddPosition = () => {
  equipdata.value.content.push({
    content: "",
    qualified: 1
  });
  // positionVisible.value = true;
};

function getList() {
  loading.value = true;

  emissionFactorquery(queryParams.value).then((response: any) => {
    typeList.value = response.data;
    total.value = response.total;
    loading.value = false;
  });
}
const removechukuList = () => {
  localStorage.removeItem("chukuList");
};
/** 取消按钮 */

/** 表单重置 */
function reset() {
  form.value = {
    id: undefined,
    dictionaryName: undefined,
    dictionaryType: undefined,
    status: "VALID",
    remarks: undefined
  };
  proxy.resetForm("dictRef");
}
/** 搜索按钮操作 */
function handleQuery(type) {
  if (type == "search") {
    queryParams.value.pageNum = 1;
  }
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    orderByColumn: "",
    isAsc: "",
    emissionFactorName: "",
    factorSource: "",
    releaseYear: "",
    orderBy: ""
  };
  dateRange.value = [];
  handleQuery("reset");
}

/** 新增按钮操作 */
function handleAdd() {
  buttonTitle.value = "新增";
  addVisible.value = true;
  equipdata.value = {
    id: "",
    emissionFactorName: "",
    numberatorUnit: "",
    denominatorUnit: "",
    factorSource: "",
    releaseYear: "",
    CO2: null,
    CH4: null,
    N2O: null,
    HFCs: null,
    PFCs: null,
    SF6: null,
    NF3: null,
    CO2e: null,
    factorValueDTOS: [],
    createByName: "",
    updateByName: "",
    documentIds: []
  };
  equipdata.value.denominatorUnit = mUnitList.value[0].itemName;
}
const handleDetail = async val => {
  detailVisible.value = true;
  const data = await emissionFactordetail({ id: val });
  equipdata.value = data;
  equipdata.value.documentIds = data.fileDTOS;
  if (data?.documentIds && data?.documentIds.length > 0) {
    data?.documentIds.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.documentIds = data?.documentIds;
  } else {
    equipdata.value.documentIds = [];
  }
};

const handleEditor = async val => {
  buttonTitle.value = "编辑";
  addVisible.value = true;

  const data = await emissionFactordetail({ id: val });
  console.log(data);
  equipdata.value = data;
  equipdata.value.releaseYear = String(data.releaseYear);
  equipdata.value.documentIds = data.fileDTOS;
  if (data?.documentIds && data?.documentIds.length > 0) {
    data?.documentIds.forEach(item => {
      item.url = item.fileUrl;
      item.name = item.originalName;
    });
    equipdata.value.documentIds = data?.documentIds;
  } else {
    equipdata.value.documentIds = [];
  }
  console.log(data?.factorValueDTOS.filter(item => item.gasType == "CO2"));
  equipdata.value.CO2 = data?.factorValueDTOS.filter(item => item.gasType == "CO2")[0].value;
  equipdata.value.CH4 = data?.factorValueDTOS.filter(item => item.gasType == "CH4")[0].value;
  equipdata.value.N2O = data?.factorValueDTOS.filter(item => item.gasType == "N2O")[0].value;
  equipdata.value.HFCs = data?.factorValueDTOS.filter(item => item.gasType == "HFCs")[0].value;
  equipdata.value.PFCs = data?.factorValueDTOS.filter(item => item.gasType == "PFCs")[0].value;
  equipdata.value.SF6 = data?.factorValueDTOS.filter(item => item.gasType == "SF6")[0].value;
  equipdata.value.NF3 = data?.factorValueDTOS.filter(item => item.gasType == "NF3")[0].value;
  equipdata.value.CO2e = data?.factorValueDTOS.filter(item => item.gasType == "CO2e")[0].value;
  getHistory(equipdata.value.emissionFactorName);
};
/** 多选框选中数据 */
function handleSelectionChange2(selection) {
  // console.log(selection);
  selectRukuList.value = selection;
}

// const addRukudetails = () => {
//   equipdata.value.details = [...equipdata.value.details, ...selectRukuList.value];
//   let seenIds = new Set();
//   let uniqueArr = [];
//   equipdata.value.details.forEach(obj => {
//     if (!seenIds.has(obj.inboundNumber)) {
//       uniqueArr.push(obj);
//       seenIds.add(obj.inboundNumber);
//     }
//   });
//   equipdata.value.details = [];
//   if (setChukuList(uniqueArr) == true) {
//     progressVisible.value = false;
//     equipdata.value.details = uniqueArr;
//   }
// };

let setChukuList = uniqueArr => {
  if (uniqueArr.length === 0) {
    PxMessage({
      message: "请选择要出库的数据",
      type: "error"
    });
    return false;
  }
  const firstname = uniqueArr[0].wasteName;
  for (let i = 1; i < uniqueArr.length; i++) {
    if (uniqueArr[i].wasteName != firstname) {
      PxMessage({
        message: "请选择相同的废弃物",
        type: "error"
      });
      return false;
    }
  }
  return true;
};

/** 提交按钮 */

const equipopenDetailsubmitForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      console.log(equipdata);
      const params = {
        emissionFactorName: equipdata.value.emissionFactorName.trim(),
        numberatorUnit: equipdata.value.numberatorUnit,
        denominatorUnit: equipdata.value.denominatorUnit,
        factorSource: equipdata.value.factorSource,
        releaseYear: equipdata.value.releaseYear,
        factorValueDTOS: [
          {
            gasType: "CO2",
            value: equipdata.value.CO2
          },
          {
            gasType: "CH4",
            value: equipdata.value.CH4
          },
          {
            gasType: "N2O",
            value: equipdata.value.N2O
          },
          {
            gasType: "HFCs",
            value: equipdata.value.HFCs
          },
          {
            gasType: "PFCs",
            value: equipdata.value.PFCs
          },
          {
            gasType: "SF6",
            value: equipdata.value.SF6
          },
          {
            gasType: "NF3",
            value: equipdata.value.NF3
          },
          {
            gasType: "CO2e",
            value: equipdata.value.CO2e
          }
        ],
        createByName: JSON.parse(localStorage.getItem("userInfo")).username,
        updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
        documentIds: equipdata.value.documentIds
      };
      if (buttonTitle.value == "新增") {
        if (params.documentIds.length > 0) {
          params.documentIds = params.documentIds.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        emissionFactorsave(params).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        removechukuList();
      } else {
        const params2 = {
          id: equipdata.value.id,
          emissionFactorName: equipdata.value.emissionFactorName.trim(),
          numberatorUnit: equipdata.value.numberatorUnit,
          denominatorUnit: equipdata.value.denominatorUnit,
          factorSource: equipdata.value.factorSource,
          releaseYear: equipdata.value.releaseYear,
          factorValueDTOS: [
            {
              gasType: "CO2",
              value: equipdata.value.CO2
            },
            {
              gasType: "CH4",
              value: equipdata.value.CH4
            },
            {
              gasType: "N2O",
              value: equipdata.value.N2O
            },
            {
              gasType: "HFCs",
              value: equipdata.value.HFCs
            },
            {
              gasType: "PFCs",
              value: equipdata.value.PFCs
            },
            {
              gasType: "SF6",
              value: equipdata.value.SF6
            },
            {
              gasType: "NF3",
              value: equipdata.value.NF3
            },
            {
              gasType: "CO2e",
              value: equipdata.value.CO2e
            }
          ],
          createByName: JSON.parse(localStorage.getItem("userInfo")).username,
          updateByName: JSON.parse(localStorage.getItem("userInfo")).username,
          documentIds: equipdata.value.documentIds
        };
        if (params2.documentIds.length > 0) {
          params2.documentIds = params2.documentIds.map(item => (item?.response?.data ? item?.response?.data.id : item.id));
        }
        emissionFactoredit(params2).then((response: any) => {
          PxMessage({
            message: `${buttonTitle.value == "新增" ? "添加成功" : "修改成功"}`,
            type: "success"
          });
          resetQuery();
          addVisible.value = false;
        });
        removechukuList();
      }
    }
  });
};
/** 删除按钮操作 */
function handleDelete(row) {
  console.log(row);
  PxMessageBox.confirm("是否确认删除？", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    confirmButtonClass: "px-button--danger",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      const data = await emissionFactordelete({ id: row.id });
      PxMessage({
        message: "删除成功",
        type: "success"
      });
      getList();
    })
    .catch(() => {});
}

/** 导入按钮操作 */
function handleImport() {
  // const dictIds = [];
  // dictIds.push(...ids.value);
  // const params = { ids: dictIds };
  // proxy.download("post", "/operation/api/v1/water/hazardWasteOut/export", params, "危险废弃物出库.xlsx");
  dialogVisible.value = true;
}
/** 导出按钮操作 */
function handleExport() {
  const params = {
    orderByColumn: queryParams.value.orderByColumn,
    isAsc: queryParams.value.isAsc,
    emissionFactorName: queryParams.value.emissionFactorName,
    factorSource: queryParams.value.factorSource,
    releaseYear: queryParams.value.releaseYear,
    orderBy: queryParams.value.orderBy
  };
  proxy.download("post", "/energy/api/v1/emissionFactor/export", params, "排放因子库信息.xlsx");

  // const dictIds = [];
  // dictIds.push(...ids.value);
  // const params = { ids: dictIds };
  // proxy.download("post", "/operation/api/v1/water/hazardWasteOut/export", params, "危险废弃物出库.xlsx");
  // dialogVisible.value = true;
}
getList();

// 历史记录
const showHistoryDialog = ref(false);
function openHistoryVersion() {
  showHistoryDialog.value = true;
}
let historyData = [];
async function getHistory(name: string, id?: number) {
  const params = {
    name,
    pageNum: 1,
    pageSize: 500
  };
  const res = await getemissionFactorHistory(params);
  if (!res) return;
  historyData = res.data;
}
// 修改年份 如有数据，回显年份数据 否则 清空下表
function changeYearVersion(val) {
  const data = cloneDeep(historyData.find(e => e.releaseYear == val));
  if (data) {
    equipdata.value = data;
    equipdata.value.releaseYear = String(data.releaseYear);
    equipdata.value.documentIds = data.fileDTOS;
    if (data?.documentIds && data?.documentIds.length > 0) {
      data?.documentIds.forEach(item => {
        item.url = item.fileUrl;
        item.name = item.originalName;
      });
      equipdata.value.documentIds = data?.documentIds;
    } else {
      equipdata.value.documentIds = [];
    }
    console.log(data?.factorValueDTOS.filter(item => item.gasType == "CO2"));
    equipdata.value.CO2 = data?.factorValueDTOS.filter(item => item.gasType == "CO2")[0].value;
    equipdata.value.CH4 = data?.factorValueDTOS.filter(item => item.gasType == "CH4")[0].value;
    equipdata.value.N2O = data?.factorValueDTOS.filter(item => item.gasType == "N2O")[0].value;
    equipdata.value.HFCs = data?.factorValueDTOS.filter(item => item.gasType == "HFCs")[0].value;
    equipdata.value.PFCs = data?.factorValueDTOS.filter(item => item.gasType == "PFCs")[0].value;
    equipdata.value.SF6 = data?.factorValueDTOS.filter(item => item.gasType == "SF6")[0].value;
    equipdata.value.NF3 = data?.factorValueDTOS.filter(item => item.gasType == "NF3")[0].value;
    equipdata.value.CO2e = data?.factorValueDTOS.filter(item => item.gasType == "CO2e")[0].value;
  } else {
    equipdata.value.id = null;
    equipdata.value.documentIds = [];
    equipdata.value.CO2 = null;
    equipdata.value.CH4 = null;
    equipdata.value.N2O = null;
    equipdata.value.HFCs = null;
    equipdata.value.PFCs = null;
    equipdata.value.SF6 = null;
    equipdata.value.NF3 = null;
    equipdata.value.CO2e = null;
  }
}
</script>
<style scoped lang="scss">
.addEquip {
  position: absolute;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.editorEquip {
  position: absolute;
  top: 5px;
  left: 0;
  width: calc(100% - 48px);
  height: calc(100% - 40px);
  margin: 24px;
  background: white;
}

.px-dialog-footer {
  position: absolute;
  bottom: 0;
  left: 0;
  z-index: 2002;
  width: 100%;
  height: 50px;
  padding-top: 10px;
  padding-right: 34px;
  text-align: right;
  background: white;
  box-shadow: 0 0 10px 0 rgb(0 0 0 / 16%);
}

.card-header {
  min-height: 40px;
  padding: 14px 15px 7px !important;
  cursor: pointer;
  user-select: none;
  background: #e7eefb;
}

.card-title {
  float: left;
  font-size: 16px;
  font-weight: 600;
  line-height: 16px;
  color: rgb(0 0 0 / 80%);
}

.card-main {
  float: left;
  margin: -3px 8px 0 5px;
  cursor: pointer;
}

.box-card1 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card2 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card3 {
  width: calc(100% - 48px);
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.box-card4 {
  width: calc(100% - 48px);
  height: 261px;
  margin: 24px;
  overflow: hidden;
  border: 1px solid #dfdfdf;
  border-radius: 4px;
}

.demo-form-inline {
  .px-input {
    --px-input-width: calc(100% - 70px);
  }

  .px-form-item {
    width: 100%;
  }

  .px-textarea__inner {
    width: calc(100% - 100px) !important;
  }

  .px-form-item__label {
    font-weight: 400 !important;
  }
}

.form-div {
  padding: 10px 24px 0;

  .px-row {
    margin-bottom: 1px;
  }
}

.px-icon {
  font-size: 16px !important;
}

:deep(.px-tabs--top .px-tabs__item.is-top.is-active) {
  border: none;

  .pane-bottom {
    line-height: 30px;
    border-bottom: 2px solid #3b82f6;
  }
}

:deep(.px-tabs .px-tabs__item) {
  .pane-bottom {
    line-height: 30px;
  }
}

.pane-line {
  position: absolute;
  top: 12px;
  right: 0;
  height: 15px;
  color: #dcdcdc;
  border-left: 1px solid #dcdcdc;
}

:deep(.custom-form-ui .px-form-item) {
  width: 250px !important;
}

.filename {
  position: absolute;
  bottom: -30px;
  width: 96px;
  overflow: hidden;
  color: rgb(166 167 172);
  text-overflow: ellipsis;
  white-space: nowrap;
}

:deep(.px-descriptions__label.px-descriptions__cell.is-bordered-label) {
  width: 166px;
  background: #e7eefb;
  border: 1px solid #dfdfdf;
}

:deep(.px-descriptions__body .px-descriptions__table.is-bordered .px-descriptions__cell) {
  border: 1px solid #dfdfdf;
}

.cell-item {
  text-align: right;
}

:deep(.px-table__header) {
  thead {
    tr {
      background-color: #e7eefb !important;

      th {
        font-size: 13px;
        font-weight: bold;
        color: #000;
        background-color: #e7eefb !important;
      }
    }
  }
}

.file-upload-wrap .file-table {
  :deep(.px-table__header) {
    thead {
      tr {
        background-color: #e7eefb !important;

        th {
          font-size: 13px;
          font-weight: bold;
          color: #000;
          background-color: #d9e9ff !important;
        }
      }
    }
  }
}

:deep(.px-table--isfixedHeader .px-table__header-wrapper .px-table-fixed-column--right) {
  background-color: #e7eefb !important;
}

.import-bottle {
  .import-bottle-title {
    box-sizing: border-box;
    display: flex;
    align-items: center;
    width: 100%;
    height: 40px;
    padding-left: 16px;
    margin-bottom: 24px;
    line-height: 1;
    color: #333;
    background-color: #fef5e6;
    border: 1px solid #f7b648;
    border-radius: 6px;

    .download {
      color: #3b82f6;
      cursor: pointer;
    }
  }

  .import-bottle-upload {
    width: 100%;
  }
}

:deep(.px-input.is-disabled .px-input__wrapper) {
  background-color: white !important;
}
</style>
